package com.uniriho.setternumber

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.RandomAccessFile
import java.nio.charset.StandardCharsets


object FileUtils{
    private val TAG = "FileUtils"

    /**
     * @param path
     * @param fileName
     * @return .
     */
    fun createFile(path: String, fileName: String): Boolean {
        val file = File(path + File.separator + fileName)
        createDirs(path)
        return if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            true
        } else {
            //
            false
        }
    }

    /**
     * @param folder
     * @return .
     */
    fun createDirs(folder: String): Boolean {
        val file = File(folder)
        if (!file.exists()) {
            val mkdirs = file.mkdirs()
            Log.i(TAG, "createDirs:  + mkdirs === $folder")
            return true
        } else {
            Log.i(TAG, "createDirs ")
        }
        return false
    }


    /**
     *
     *
     * @param path
     * @param name
     * @return .
     */
    fun readFileI(path: String?, name: String?): String? {
        //默认编码格式 StandardCharsets.UTF_8;
        val file = File(path, name)
        if (!file.exists()) {
            return null
        }
        val builder = StringBuilder("")
        try {
            val reader =
                BufferedReader(InputStreamReader(FileInputStream(file), StandardCharsets.UTF_8))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                builder.append(line)
                builder.append("\n")
            }
            reader.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return builder.toString()
    }


    /**
     * @param content   .
     * @param path      .
     * @param fileName  .
     * @param isReWrite
     */
    fun writeFileO(content: String?, path: String, fileName: String, isReWrite: Boolean): Int {
        val file = File(path + fileName)
        if (!file.exists()) {
            createFile(path, fileName)
        }
        return try {
            val ops = FileOutputStream(file, isReWrite)
            val opsw = OutputStreamWriter(ops, StandardCharsets.UTF_8)
            // byte[] bytes = content.getBytes();
            opsw.write(content)
            opsw.close()
            ops.close()
            1
        } catch (e: IOException) {
            e.printStackTrace()
            -1
        }
    }

}